//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.dao.AdminDao;
import com.wsd.smartcarwasher.dao.UserRoleDao;
import com.wsd.smartcarwasher.domain.Admin;
import com.wsd.smartcarwasher.domain.UserRoleDO;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Service
public class AdminService {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);
    @Resource
    private AdminDao adminDao;

    @Resource
    private UserRoleDao userRoleMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private HttpServletRequest request;

    public AdminService() {
    }

    public int addAdmin(Admin admin) {
        this.passwordEncryption(admin);
        int row = this.adminDao.addAdmin(admin);
        if(row>0){
            List<Long> roles = admin.getRoleIds();
            userRoleMapper.removeByUserId(admin.getId().longValue());
            List<UserRoleDO> list = new ArrayList<>();
            for (Long roleId : roles) {
                UserRoleDO ur = new UserRoleDO();
                ur.setUserId(admin.getId().longValue());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                logger.info("开始添加用户角色");
                userRoleMapper.batchSave(list);
            }
        }
        return row;
    }

    public ModelMap loginByPassword(String cellphone, String password) {
        Subject subject = SecurityUtils.getSubject();
        HashMap resultMap = new HashMap();
        Admin admin=this.adminDao.getAdminByCellphone(cellphone);
        try {
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(cellphone, password, false);
                subject.login(token);
            }
            resultMap.put("token", subject.getSession().getId());
        } catch (IncorrectCredentialsException var6) {
            return ReturnUtil.Error("密码错误");
        } catch (LockedAccountException var7) {
            return ReturnUtil.Error("用户状态异常");
        } catch (AuthenticationException var8) {
            return ReturnUtil.Error("用户不存在");
        } catch (Exception var9) {
            logger.error("登录失败", var9);
            return ReturnUtil.Error("登录失败");
        }
//        //如果是加盟商管理员，登录后存入session
//        if(admin.getPartnerId()!=null) {
//            request.getSession().setAttribute("ispartnerId", admin.getPartnerId());
//        }
        return ReturnUtil.Success("登陆成功", resultMap);
    }

    public Admin getAdminByNickname(String nickname) {
        return this.adminDao.getAdminByNickname(nickname);
    }

    public Admin getAdminByCellphone(String cellphone) {
        return this.adminDao.getAdminByCellphone(cellphone);
    }

    private void passwordEncryption(Admin admin) {
        String salt = String.valueOf(System.currentTimeMillis());
        admin.setSalt(salt);
        String password = (new SimpleHash("MD5", admin.getPassword(), admin.getSalt(), 2)).toString();
        admin.setPassword(password);
    }

    public boolean hasAdminWithCellphone(String cellphone) {
        return this.adminDao.hasAdminWithCellphone(cellphone) != null;
    }

    public List<Admin> queryAdminWithAuthLevel(String authLevel) {
        List<Admin> admins = this.adminDao.queryAdminWithAuthlevel(authLevel);
        admins.forEach(admin -> {
            admin.setRoleIds(userRoleMapper.listRoleId(admin.getId().longValue()));
        });
        return admins == null ? Collections.emptyList() : admins;
    }

    public Admin getAdminById(int id) {
        return this.adminDao.getAdminById(id);
    }

    public int updateAdmin(Admin admin) {

        if (StringUtils.isNotBlank(admin.getPassword())) {
            if(this.adminDao.getAdminById(admin.getId()).getPassword().equals(admin.getPassword()))
            {
                admin.setSalt((String)null);
                userRoleMapper.removeByUserId(admin.getId().longValue());
                List<Long> roles = admin.getRoleIds();
                List<UserRoleDO> list = new ArrayList<>();
                for (Long roleId : roles) {
                    UserRoleDO ur = new UserRoleDO();
                    ur.setUserId(admin.getId().longValue());
                    ur.setRoleId(roleId);
                    list.add(ur);
                }
                if (list.size() > 0) {
                    userRoleMapper.batchSave(list);
                }
                return this.adminDao.updateAdmin(admin);
            }


            admin.setPassword((new SimpleHash("MD5", admin.getPassword(), admin.getSalt(), 2)).toString());
        }

        admin.setSalt((String)null);
        userRoleMapper.removeByUserId(admin.getId().longValue());
        List<Long> roles = admin.getRoleIds();
        List<UserRoleDO> list = new ArrayList<>();
        for (Long roleId : roles) {
            UserRoleDO ur = new UserRoleDO();
            ur.setUserId(admin.getId().longValue());
            ur.setRoleId(roleId);
            list.add(ur);
        }
        if (list.size() > 0) {
            userRoleMapper.batchSave(list);
        }
        return this.adminDao.updateAdmin(admin);
    }

    public int deleteAdmin(int id) {
        userRoleMapper.removeByUserId(Integer.valueOf(id).longValue());
        return this.adminDao.deleteAdmin(id);
    }

    public int updatePassword(Admin admin) {
        return this.adminDao.updateAdmin(admin);
    }

}




/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.dao.AdminDao;
import com.wsd.smartcarwasher.domain.Admin;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminService {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);

    @Resource
    private AdminDao adminDao;

    @Resource
    private RedisService redisService;

    public int addAdmin(Admin admin) {
        passwordEncryption(admin);
        return adminDao.addAdmin(admin);
    }

    //根据账号密码登录
    public ModelMap loginByPassword(Admin admin) {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> resultMap = new HashMap<>();

        try {
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(admin.getNickname(), admin.getPassword());
                token.setRememberMe(true);
                subject.login(token);
            }
            resultMap.put("token", subject.getSession().getId());
            resultMap.put("userInfo", admin);
            redisService.put(subject.getSession().getId().toString(), admin.getId().toString(), 9600);
        } catch (IncorrectCredentialsException e) {
            return ReturnUtil.Error("密码错误");
        } catch (LockedAccountException e) {
            return ReturnUtil.Error("用户状态异常");
        } catch (AuthenticationException e) {
            return ReturnUtil.Error("用户不存在");
        } catch (Exception e) {
            logger.error("登录失败", e.getMessage());
            return ReturnUtil.Error("登录失败");
        }
        return ReturnUtil.Success("登陆成功", resultMap);
    }

    public Admin getAdminByNickname(String nickname) {
        return adminDao.getAdminByNickname(nickname);
    }

    private void passwordEncryption(Admin admin) {
        String salt = System.currentTimeMillis() + "";
        admin.setSalt(salt);
        //加密密码
        String password = new SimpleHash(Global.HASH_ALGORITHM_NAME, admin.getPassword(), admin.getSalt(), Global.HASH_ITERATIONS).toString();
        admin.setPassword(password);
    }

    public boolean hasAdminWithCellphone(String cellphone) {
        return adminDao.hasAdminWithCellphone(cellphone) != null;
    }

    public List<Admin> queryAdminWithAuthLevel(String authLevel) {
        List<Admin> admins = adminDao.queryAdminWithAuthlevel(authLevel);
        if (admins == null) {
            return Collections.emptyList();
        }
        return admins;
    }

    public Admin getAdminById(int id) {
        return adminDao.getAdminById(id);
    }

    public int updateAdmin(Admin admin) {
        if (StringUtils.isNotBlank(admin.getPassword())) {
            admin.setPassword(new SimpleHash(Global.HASH_ALGORITHM_NAME, admin.getPassword(), admin.getSalt(), Global.HASH_ITERATIONS).toString());
        }
        return adminDao.updateAdmin(admin);
    }

    public int deleteAdmin(int id) {
        return adminDao.deleteAdmin(id);
    }
}
*/
